跳到主要内容

242 有效的字母异位词

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn96us/

https://leetcode.cn/problems/valid-anagram/description/

cost: 3m

class Solution {
public:
bool isAnagram(string s, string t) {
unordered_map<char, int> m;
for (const char ch : s) {
m[ch]++;
}
for (const char ch : t) {
if (!m.count(ch) || m[ch] == 0) {
return false;
}
m[ch]--;
if (m[ch] == 0) {
m.erase(ch);
}
}
return m.empty();
}
};
  • 时间复杂度:O(n1+n2)
  • 空间复杂度:O(∣S∣),其中 S 是字符集